package main.java.com.chankudo.thread;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
/**
 * fork/join 框架
 * 多线程执行可以被拆解的任务，继承 RecursiveTask 的任务
 * 执行该任务时有返回值
 */
public class SimpleRecursiveTask extends RecursiveTask<Integer>{
    public final int MAX_V = 50;
    private int value;
    private int stopV;
    

    public SimpleRecursiveTask(int left, int value) {
        this.stopV = left;
        this.value = value;
    }

    @Override
    protected Integer compute() {
        if(value - stopV <= MAX_V){ // 小于阈值，不拆分任务
            int sum_ = 0;
            for(int i=stopV; i<value; i++){
                sum_ += value;
            }
            return sum_;

        }else{// 不然就拆分任务
            int mid = (value+stopV)/2;
            SimpleRecursiveTask lftTask = new SimpleRecursiveTask(stopV,mid);
            SimpleRecursiveTask rgtTask = new SimpleRecursiveTask(mid+1, value);
            invokeAll(lftTask, rgtTask);
            return lftTask.join() + rgtTask.join();
        }
    }

    public static void main(String[] args) {
        SimpleRecursiveTask task = new SimpleRecursiveTask(0, 1023);
        ForkJoinPool pool = new ForkJoinPool();
        pool.invoke(task);
        System.out.println(task.join());
    }
    
}
